package com.jic.member.controller.rest;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.enums.RedisKey;
import com.jic.member.common.util.BeanUtil;
import com.jic.member.entity.DisCashLog;
import com.jic.member.entity.DisCommissionInfo;
import com.jic.member.entity.MememberUser;
import com.jic.member.request.*;
import com.jic.member.response.*;
import com.jic.member.service.DisCashLogService;
import com.jic.member.service.DisCommissionInfoService;
import com.jic.member.service.MememberUserService;
import com.jic.order.api.DistributionOrderApi;
import com.jic.order.response.OrderGoodsInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("apiDistribution")
@Api(value = "APi-分销中心", tags = "APi-分销中心")
@Slf4j
public class ApiDistributionController {

    @Resource
    private RedisClientTemplate redisClientTemplate;
    @Resource
    private MememberUserService mememberUserService;

    @Resource
    private DisCommissionInfoService disCommissionInfoService;

    @Resource
    private DisCashLogService disCashLogService;

    @Resource
    private DistributionOrderApi distributionOrderApi;

    @ApiOperation("查询分销员基本信息")
    @ResponseBody
    @PostMapping("getDistributionUserInfo")
    public RestResult<DistributorRestResponse> getDistributionUserInfo(@RequestBody DistributionRestRequest distributionRestRequest) {
        log.info("开始进入查询分销员基本信息=================》》" + distributionRestRequest.toString());
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + distributionRestRequest.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        DistributorRestResponse distributorRestResponse = new DistributorRestResponse();
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }
        MememberUser mememberUser = mememberUserService.queryByPrimaryKey(member.getId());
        if (mememberUser == null) {
            return RestResult.error("9999", "用户不存在");
        } else {
            distributorRestResponse.setId(member.getId());
            distributorRestResponse.setNickName(member.getNickName());

            //上级分销代理信息
            MememberUser mememberUser1 = mememberUserService.queryByPrimaryKey(mememberUser.getAllocationPid());
            if (mememberUser1 != null) {
                distributorRestResponse.setPid(mememberUser1.getId());
                distributorRestResponse.setPNickName(mememberUser1.getNickName());
            }

            //可提现金额
            BigDecimal withdrawalMoney = BigDecimal.ZERO;
            DisCommissionInfo disCommissionInfo = new DisCommissionInfo();
            disCommissionInfo.setMemberId(member.getId());
            disCommissionInfo.setStatus(3);
            disCommissionInfo.setToken(distributionRestRequest.getToken());
            BigDecimal commissionCount = disCommissionInfoService.getCommissionCount(disCommissionInfo);
            if (commissionCount != null) {
                withdrawalMoney = commissionCount;
            }
            distributorRestResponse.setWithdrawalMoney(withdrawalMoney);

            //已提现金额
            BigDecimal alerdyWithdrawalMoney = BigDecimal.ZERO;
            DisCashLog disCashLog = new DisCashLog();
            disCashLog.setStatus(8);
            disCashLog.setMemberId(member.getId());
            BigDecimal withdrawalCount = disCashLogService.getWithdrawalCount(disCashLog);
            if (withdrawalCount != null) {
                alerdyWithdrawalMoney = withdrawalMoney;
            }
            distributorRestResponse.setAlerdyWithdrawalMoney(alerdyWithdrawalMoney);

            //未结算佣金
            BigDecimal notWithdrawalMoney = BigDecimal.ZERO;
            DisCommissionInfo disCommissionInfo1 = new DisCommissionInfo();
            disCommissionInfo1.setMemberId(member.getId());
            BigDecimal commissionCount1 = disCommissionInfoService.getCommissionCount(disCommissionInfo1);
            if (commissionCount1 != null && commissionCount != null) {
                notWithdrawalMoney = commissionCount1.subtract(commissionCount);
            }
            distributorRestResponse.setNotWithdrawalMoney(notWithdrawalMoney);
        }
        return RestResult.success(distributorRestResponse);
    }


    @ApiOperation("累计佣金")
    @ResponseBody
    @PostMapping("getCommissionCount")
    public RestResult<BigDecimal> getCommissionCount(@RequestBody DistributionRestRequest distributionRestRequest) {
        log.info("开始进入累计佣金查询=================》》" + distributionRestRequest.toString());
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + distributionRestRequest.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }
        //累计佣金
        BigDecimal commissionCount = BigDecimal.ZERO;
        DisCommissionInfo disCommissionInfo = new DisCommissionInfo();
        disCommissionInfo.setMemberId(member.getId());
        disCommissionInfo.setToken(distributionRestRequest.getToken());
        BigDecimal commissionCount1 = disCommissionInfoService.getCommissionCount(disCommissionInfo);
        if (commissionCount1 != null) {
            commissionCount = commissionCount1;
        }
        return RestResult.success(commissionCount);
    }


    @ApiOperation("累计明细")
    @ResponseBody
    @PostMapping("getCommissionListPage")
    public RestResult<PageResult<DisCommissionInfo>> getCommissionListPage(@RequestBody CommissionInfoQueryRestResquest resquest) {
        log.info("开始进入累计明细查询=================》》" + resquest.toString());
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + resquest.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }
        Page page = new Page();
        page.setLimit(resquest.getLimit());
        page.setStart(resquest.getStart());
        DisCommissionInfo disCommissionInfo = new DisCommissionInfo();
        disCommissionInfo.setMemberId(member.getId());
        disCommissionInfo.setStatus(resquest.getStatus());
        PageResult<DisCommissionInfo> result = disCommissionInfoService.queryPage(disCommissionInfo, page);
        return RestResult.success(result);
    }


    @ApiOperation("累计提现/可提现/不可提现")
    @ResponseBody
    @PostMapping("getWithdrawalCount")
    public RestResult<ApplyCountRestResponse> getWithdrawalCount(@RequestBody DistributionRestRequest distributionRestRequest) {
        log.info("开始进入累计提现/可提现/不可提现查询=================》》" + distributionRestRequest.toString());
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + distributionRestRequest.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        ApplyCountRestResponse applyCountRestResponse = new ApplyCountRestResponse();
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }
        //累计提现
        BigDecimal accumulativeWithdrawal = BigDecimal.ZERO;
        DisCashLog disCashLog = new DisCashLog();
        disCashLog.setMemberId(member.getId());
        disCashLog.setStatus(8);
        BigDecimal withdrawalCount = disCashLogService.getWithdrawalCount(disCashLog);
        if (withdrawalCount != null) {
            accumulativeWithdrawal = withdrawalCount;
        }
        applyCountRestResponse.setAccumulativeWithdrawal(accumulativeWithdrawal);


        //可提现
        BigDecimal withdrawaAmount = BigDecimal.ZERO;
        DisCommissionInfo disCommissionInfo = new DisCommissionInfo();
        disCommissionInfo.setStatus(2);
        disCommissionInfo.setMemberId(member.getId());
        BigDecimal commissionCount = disCommissionInfoService.getCommissionCount(disCommissionInfo);
        if (commissionCount != null) {
            withdrawaAmount = commissionCount;
        }
        applyCountRestResponse.setWithdrawaAmount(withdrawaAmount);

        //不可提现
        BigDecimal notWithdrawaAmount = BigDecimal.ZERO;
        DisCommissionInfo disCommissionInfo1 = new DisCommissionInfo();
        disCommissionInfo1.setMemberId(member.getId());
        BigDecimal commissionCount1 = disCommissionInfoService.getCommissionCount(disCommissionInfo1);
        if (commissionCount1 != null) {
            notWithdrawaAmount = commissionCount1.subtract(withdrawaAmount);
        }
        applyCountRestResponse.setNotWithdrawaAmount(notWithdrawaAmount);

        return RestResult.success(applyCountRestResponse);
    }


    @ApiOperation("提现明细")
    @ResponseBody
    @PostMapping("getWithdrawalListPage")
    public RestResult<PageResult<DisCashLog>> getWithdrawalListPage(@RequestBody ApplyQueryRestResquest resquest) {
        log.info("开始进入提现明细查询=================》》" + resquest.toString());
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + resquest.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }
        Page page = new Page();
        page.setLimit(resquest.getLimit());
        page.setStart(resquest.getStart());
        DisCashLog disCashLog = new DisCashLog();
        disCashLog.setMemberId(member.getId());
        disCashLog.setStatus(resquest.getApplyStatus());
        PageResult<DisCashLog> result = disCashLogService.queryPage(disCashLog, page);
        return RestResult.success(result);
    }

    @ApiOperation("我的团队")
    @ResponseBody
    @PostMapping("getMyTeam")
    public RestResult<PageResult<MemberUserRestResponse>> getMyTeam(@RequestBody MyTeamRestResquest resquest) {
        log.info("开始进入提现明细查询=================》》" + resquest.toString());
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + resquest.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }

        Page page = new Page();
        page.setLimit(resquest.getLimit());
        page.setStart(resquest.getStart());
        MememberUser mememberUser = new MememberUser();
        mememberUser.setAllocationPid(member.getId());
        mememberUser.setDeleteFlag(0);
        mememberUser.setStatus(1);
        PageResult<MememberUser> result = mememberUserService.listRestPage(mememberUser, page);
        List<MemberUserRestResponse> memberRestResponseList = result.getRows().stream().map(temp -> {
            MemberUserRestResponse memberUserRestResponse = BeanUtil.copy(temp, MemberUserRestResponse.class);
            return memberUserRestResponse;
        }).filter(item -> item != null).collect(Collectors.toList());

        PageResult<MemberUserRestResponse> pageResult = new PageResult<>();
        pageResult.setRows(memberRestResponseList);
        pageResult.setTotal(result.getTotal());
        return RestResult.success(pageResult);
    }


    @ApiOperation("我的推广二维码")
    @ResponseBody
    @PostMapping("queryDistributorShare")
    public RestResult<DistributorShareResponse> queryDistributorShare(@RequestBody DistributorShareRequest request) {
        return mememberUserService.queryDistributorShare(request);
    }

    @ApiOperation("提现")
    @ResponseBody
    @PostMapping("getWithdrawalInfo")
    public RestResult<WithdrawalCountRestResponse> getWithdrawalInfo(@RequestBody DistributorShareRequest request) {
        log.info("开始进入提现查询=================》》" + request.toString());
        String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + request.getToken());
        MememberUser member = JSONArray.parseObject(memStr, MememberUser.class);
        WithdrawalCountRestResponse withdrawalCountRestResponse = new WithdrawalCountRestResponse();
        if (member == null) {
            return RestResult.error("4000", "登录失效");
        }

        //可提现
        BigDecimal withdrawaAmount = BigDecimal.ZERO;
        DisCommissionInfo disCommissionInfo = new DisCommissionInfo();
        disCommissionInfo.setStatus(2);
        disCommissionInfo.setMemberId(member.getId());
        disCommissionInfo.setToken(request.getToken());
        BigDecimal commissionCount = disCommissionInfoService.getCommissionCount(disCommissionInfo);
        if (commissionCount != null) {
            withdrawaAmount = commissionCount;
        }

        //已申请佣金
        BigDecimal commissionApplied = BigDecimal.ZERO;
        DisCashLog disCashLog = new DisCashLog();
        disCashLog.setMemberId(member.getId());
        disCashLog.setStatus(1);
        BigDecimal withdrawalCount = disCashLogService.getWithdrawalCount(disCashLog);
        if (withdrawalCount != null) {
            commissionApplied = withdrawalCount;
        }
        withdrawalCountRestResponse.setCommissionApplied(commissionApplied);
        withdrawalCountRestResponse.setWithdrawableCommission(withdrawaAmount.subtract(commissionApplied));
        //待打款
        BigDecimal commissionPaying = BigDecimal.ZERO;
        DisCashLog disCashLog1 = new DisCashLog();
        disCashLog1.setMemberId(member.getId());
        disCashLog1.setStatus(4);
        BigDecimal withdrawalCount1 = disCashLogService.getWithdrawalCount(disCashLog1);
        if (withdrawalCount1 != null) {
            commissionPaying = withdrawalCount1;
        }
        withdrawalCountRestResponse.setCommissionPaying(commissionPaying);


        //成功提现佣金
        BigDecimal commissionSuccess = BigDecimal.ZERO;
        DisCashLog disCashLog2 = new DisCashLog();
        disCashLog2.setMemberId(member.getId());
        disCashLog2.setStatus(8);
        BigDecimal withdrawalCount2 = disCashLogService.getWithdrawalCount(disCashLog2);
        if (withdrawalCount2 != null) {
            commissionSuccess = withdrawalCount2;
        }
        withdrawalCountRestResponse.setCommissionSuccess(commissionSuccess);


        //未收获佣金
        BigDecimal commissionUnearned = BigDecimal.ZERO;
        DisCashLog disCashLog3 = new DisCashLog();
        disCashLog3.setMemberId(member.getId());
        BigDecimal withdrawalCount3 = disCashLogService.getWithdrawalCount(disCashLog3);
        if (withdrawalCount3 != null && withdrawalCount2 != null) {
            commissionUnearned = withdrawalCount3.subtract(withdrawalCount2);
        }
        withdrawalCountRestResponse.setCommissionUnearned(commissionUnearned);


        //未结算佣金
        BigDecimal commissionUnsettled = BigDecimal.ZERO;
        DisCommissionInfo disCommissionInfo1 = new DisCommissionInfo();
        disCommissionInfo1.setMemberId(member.getId());
        BigDecimal commissionCount1 = disCommissionInfoService.getCommissionCount(disCommissionInfo1);
        if (commissionCount1 != null && withdrawaAmount != null) {
            commissionUnsettled = commissionCount1.subtract(withdrawaAmount);
        }
        withdrawalCountRestResponse.setCommissionUnsettled(commissionUnsettled);


        //满多少可提现 暂无 写死
        BigDecimal commissionAvailable = BigDecimal.ZERO;
        withdrawalCountRestResponse.setCommissionAvailable(commissionAvailable);

        return RestResult.success(withdrawalCountRestResponse);
    }

    @ApiOperation("我要提现")
    @ResponseBody
    @PostMapping("saveApply")
    public RestResult<Boolean> saveApply(@RequestBody DisCashLogSaveRequest request) {
        return disCashLogService.saveDisCashLog(request);
    }


    @ApiOperation("分销订单")
    @ResponseBody
    @PostMapping("getDistributionOrderListPage")
    public RestResult<PageResult<DistributionOrderRestResponse>> getDistributionOrderListPage(@RequestBody DistributionRestRequest resquest) {
        log.info("开始进入分销订单查询=================》》" + resquest.toString());
        return disCommissionInfoService.getDistributionOrderListPage(resquest);
    }


    @ApiOperation("添加上级或者下级")
    @ResponseBody
    @PostMapping("addHigherOrLower")
    public RestResult<Boolean> addHigherOrLower(@RequestBody DistributionRestRequest request) {
        return mememberUserService.addHigherOrLower(request);
    }

}
